package queue;

public class SymbolTableSort2<key extends Comparable<key>, value> {
    private Node head;
    private int N;

    public SymbolTableSort2() {
        this.head = new Node(null, null, null);
        this.N = 0;
    }

    public int size() {
        return N;
    }

    public value get(key key) {
        if (N == 0) {
            return null;
        }
        Node tem = head;
        while (tem.next != null) {
            tem = tem.next;
            if (tem.key.equals(key)) {
                return tem.value;
            }
        }
        return null;
    }

    public void put(key key, value value) {
       Node before = head;
       Node curr = head.next;
       while (curr != null && key.compareTo(curr.key)>0){
           before = curr;
           curr =curr.next;
       }
       if (curr != null && key.compareTo(curr.key)==0){
           curr.value =value;
           return;
       }
       Node newNode = new Node(key,value,curr);
       before.next = newNode;
    }

    public void delete(key key) {
        if (key == null || N == 0) {
            throw new RuntimeException("表为空，或者输入的键错误");
        }
        Node tem = head;

        //我的实现方式，占用了较大的内存
      /*  while (tem.next != null) {
            Node before = tem;
            tem = tem.next;
            if (tem.key.equals(key)) {
                before.next = tem.next;
                N--;
                break;
            }
        }*/
        //别人的方法，更好
        while (tem.next != null){
            if (tem.next.key.equals(key)){
                tem.next =tem.next.next;
                N--;
                return;
            }
            tem =tem.next;
        }
    }

    private class Node {
        key key;
        value value;
        Node next;

        public Node(key key, value value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }
}
